/*
 * Name 		: Chang Hyun Park
 * Student ID	: 2007******
 * Major		: Computer Engineering
 * Year			: 3rd Year
 * Subject		: File Management
 * Filename		: clock.c
 */

#include "header.h"

int hit(int temp_num, node* head)
{
	node* temp;
	int flag=0;

	temp=head;
	do
	{//search from head until node before head(circular)
		if(temp_num==temp->bufVal)
		{
			temp->reference = 1;
			return 1;//Hit
		}
		temp=temp->next;
	}while(temp!=head);
	return flag;//Flag returns 0 if all references are full but no hit
				//hit returns 1 if there is a hit.
}

 node* find_victim_replace(node** temp, int data)
 {//using double pointer for node** temp so that we can actually change the
  //address which victim points to after each find_victim_replace();
	 node* victim;
	 victim = *temp;
	 victim = victim->next;
	 while(victim->reference==1)
	 {//Loop through the linked list until we find a victim to replace
		 victim->reference=0;//Tolerate once.. (give one more chance)
		 victim = victim->next;
	 }
	 victim->reference = 0;//replace
	 victim->bufVal=data;
   
	 return victim;
 }
//clock 구현
int clock(int temp_num, node* head, node** victim, int* filedata)
{
	int hitreturn;

	hitreturn = hit(temp_num,head);
	if(hitreturn==1)//Means that it was hit
	{
		//clock_hit_count++;
		return 1;
	}
	else if(hitreturn==0)//Means a no-hit
	{
		*victim = find_victim_replace(*victim, temp_num);
		//clock_miss_count++;
		return 0;
	}
	return -1;
}
